package com.snsoft.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.snsoft.util.Constants;

/**
 * 
 * @author 慎伟康
 * 
 * @date 2017年12月22日 上午11:29:24
 * 
 * @Description TODO
 *    编码拦截器，设置请求响应编码
 */
public class EncodeInterceptor extends HandlerInterceptorAdapter {

	private final static Logger logger = LoggerFactory.getLogger(EncodeInterceptor.class);
	
	/** 记录下请求处理的时间 */
	private static ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<Long>();
	
	/**
	 * 预处理回调方法，实现控制器的预处理（如登录检查），第三个参数为响应的控制器
	 * 返回值：true表示继续流程,false表示流程中断
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		logger.debug("------preHandle------");

		/*
		 * 设置编码
		 * get请求需要设置tomcat文件夹下的conf/servler.xml，添加URIEncoding="UTF-8"
		 * <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" 
		 * redirectPort="8443" URIEncoding="UTF-8"/>
		 */
		request.setCharacterEncoding(Constants.CHARSET);
		response.setCharacterEncoding(Constants.CHARSET);
		
		//请求开始时间
		long beginTime = System.currentTimeMillis();
		startTimeThreadLocal.set(beginTime);//线程绑定变量
		
		return true;
	}

	/**
	 * 后处理回调方法，实现控制器的后处理，但在渲染视图之前
	 */
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		logger.debug("------postHandle------");
		super.postHandle(request, response, handler, modelAndView);
	}

	/**
	 * 整个请求处理完毕回调方法，即在视图渲染完毕时回调
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		//请求结束时间
		long endTime = System.currentTimeMillis();
		long beginTime = startTimeThreadLocal.get();//得到线程绑定的开始时间
		long time = endTime - beginTime;
		logger.info("[" + request.getRequestURI() + "]处理请求使用了" + time + "ms");
		
		logger.debug("------afterCompletion------");
		super.afterCompletion(request, response, handler, ex);
	}

	/**
	 * 用于处理异步请求，当控制器中有异步请求方法的时候会触发该方法时
	 */
	@Override
	public void afterConcurrentHandlingStarted(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		logger.debug("------afterConcurrentHandlingStarted------");
		super.afterConcurrentHandlingStarted(request, response, handler);
	}
}
